package com.sky.web;

import com.sky.constant.AuthConstant;
import com.sky.dto.member.UmsMemberVO;
import com.sky.service.OmsOrderService;
import com.sky.vo.OrderSubmitResponseVo;
import com.sky.vo.OrderSubmitVo;
import com.sky.vo.SettlementVo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Objects;

/**
 * @author Administrator
 * 结算页
 */
@Controller
public class SettlementController {
    @Resource
    public OmsOrderService omsOrderService;

    /**
     * @author zhl
     * @description 获取当前登录用户的商品结算信息
     * @date 2024/8/29 14:39
     */
    @GetMapping("/settlement.html")
    public String index(HttpSession session, Model model) throws Exception{
        UmsMemberVO umsMemberVO = (UmsMemberVO)session.getAttribute(AuthConstant.SESSION_USER_INFO);
        if (Objects.nonNull(umsMemberVO)){
            SettlementVo settlementVo = omsOrderService.getUserSettlement();
            model.addAttribute("settlement", settlementVo);
            return "settlement";
        } else {
            // 用户未登录，跳转到登录页进行登录
            return "redirect:http://auth.skymall.com/login.html";
        }
    }

    /**
     * @author zhl
     * @description 生成当前登录用户的商品订单信息
     * @date 2024/8/29 14:39
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo orderSubmitVo, Model model, RedirectAttributes attributes) throws Exception{
        OrderSubmitResponseVo vo = null;
        try {
            vo = omsOrderService.submitOrder(orderSubmitVo);
        } catch (Exception e) {
            attributes.addFlashAttribute("msg", "分布式事务引起的异常");
            return "redirect:http://order.skymall.com/settlement.html";
        }
        if (vo.getCode() == 0){
            model.addAttribute("order", vo.getOmsOrder());
            return "waiting";
        } else {
            Integer code = vo.getCode();
            String msg = "下订单失败!";
            switch (code){
                case 1: msg = msg + "验证token失败"; break;
                case 2: msg = msg + "验价失败"; break;
                case 3: msg = msg + "库存不足"; break;
                default: msg = msg + "未知错误"; break;
            }
            attributes.addFlashAttribute("msg", msg);
            return "redirect:http://order.skymall.com/settlement.html";
        }
    }
}
